﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppleAutoBuy.Common;
using SHDocVw;
using mshtml;
using System.Threading;
using AppleAutoBuy.Model;
using System.Runtime.InteropServices;

namespace AppleAutoBuy
{
    public partial class AppleAutoBuy : Form
    {
        public const int MaxCount = 1000;
        public const int Interval = 5;

        #region Ctor

        public AppleAutoBuy()
        {
            InitializeComponent();
        }

        #endregion

        #region PageLoad

        private void AppleAutoBuy_Load(object sender, EventArgs e)
        {
            BindData();
        }

        #endregion

        #region BindData

        protected void BindData()
        {
            UsersComboBox.ValueMember = "AppleID";
            UsersComboBox.DisplayMember = "AppleID";
            UsersComboBox.DataSource = ResourceManager.AppleData.Users;

            ProductsComboBox.ValueMember = "ID";
            ProductsComboBox.DisplayMember = "Name";
            ProductsComboBox.DataSource = ResourceManager.AppleData.Products;

            StoresComboBox.ValueMember = "ID";
            StoresComboBox.DisplayMember = "Name";
            StoresComboBox.DataSource = ResourceManager.AppleData.Stores;

        }

        #endregion

        #region Events

        private void StartButton_Click(object sender, EventArgs e)
        {
            MainWebBrowser.Navigate(ResourceManager.AppleData.StartUrl,false);
            MainWebBrowser.Navigated += new WebBrowserNavigatedEventHandler(MainWebBrowser_Navigated);
            MainWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(MainWebBrowser_DocumentCompleted); 
            State = ProcessState.Started;
        }

        void MainWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
             
            if (MainWebBrowser.Document != null && MainWebBrowser.Document.Window != null)
            {
                MainWebBrowser.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

                //if (MainWebBrowser.Document.Body == null)
                //    MainWebBrowser.Refresh( WebBrowserRefreshOption.Completely );
            }

        }

        void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        string storeName
        {
            get;
            set;
        }
        void MainWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            InternetExplorer ie = (InternetExplorer)MainWebBrowser.ActiveXInstance;
            
            storeName = (StoresComboBox.SelectedItem as Store).Name; 
            if (State == ProcessState.Started && e.Url.ToString().ToLower() == ResourceManager.AppleData.StartUrl.ToLower())
            { 
                HtmlDocument document = MainWebBrowser.Document;
                IHTMLWindow2 wind2 = (IHTMLWindow2)MainWebBrowser.Document.Window.DomWindow;
                IHTMLDocument doc = (IHTMLDocument)document.DomDocument;
                IntPtr doc2Hanlde = MainWebBrowser.Handle;
                IHTMLDocument2 ddd2 = Util.GetIDoc2FromHandle(doc2Hanlde);
                doc3 = (IHTMLDocument3)doc; 

                AppleAction checkStore = CheckStore; State = ProcessState.Open;
                checkStore.BeginInvoke(doc, doc2Hanlde, new AsyncCallback(result =>
                {
                    if (result.IsCompleted)
                    {
                        bool isChecked = checkStore.EndInvoke(result);
                        if (isChecked)
                        {
                            HtmlElement element = document.GetElementById("storePopUpButton.ID148");
                            element.Focus(); 
                            Util.SetState(VirtualKeys.VK_DOWN, true); 
                            AppleAction confirmStore = ConfirmStore;
                            confirmStore.BeginInvoke(doc, doc2Hanlde, new AsyncCallback(cresult =>
                            {
                                if (cresult.IsCompleted)
                                {
                                    if (confirmStore.EndInvoke(cresult))
                                    {
                                        AppleAction selectProductCate = SelectProductCate;
                                        selectProductCate.BeginInvoke(doc, doc2Hanlde, new AsyncCallback(pdresult =>
                                        {
                                            if (pdresult.IsCompleted 
                                                && selectProductCate.EndInvoke(pdresult))
                                            { 
                                            }
                                        }), null);
                                    }
                                }
                            }), null);
                        }
                    }
                }), null);                
                
            }
        }


        #endregion

        delegate void dd();
         

        #region Properties

        public InternetExplorer IE
        { get; private set; }

        public ProcessState State
        { get; private set; }
        #endregion


        #region Actions

        public delegate bool AppleAction(IHTMLDocument doc, IntPtr doc2Handle);

        public bool CheckStore(IHTMLDocument doc, IntPtr doc2Handle)
        {
            IHTMLWindow2 win2 = Util.GetIDoc2FromHandle(doc2Handle).parentWindow;
            win2.execScript("alert(1)", "JavaScript");
            IHTMLDocument3 doc3 = (IHTMLDocument3)doc;
            bool result = false;
            int i = 0;
            while (i < MaxCount)
            {
                IHTMLElement element = doc3.getElementById("storePopUpButton.ID148");
                if (element != null)
                {
                    IHTMLSelectElement select = (IHTMLSelectElement)element;

                    for (int j = 0; j < select.length; j++)
                    {
                        IHTMLElement item = (IHTMLElement)select.item(j);
                        if (item != null && item.innerText == storeName)
                        {
                            if (j > 0)
                                select.selectedIndex = j - 1;
                            result = true;
                            break;
                        }
                    }
                }
                i++;
            }

            return result;
        }

        public bool ConfirmStore(IHTMLDocument doc, IntPtr doc2Handle)
        {
            IHTMLDocument3 doc3 = (IHTMLDocument3)doc;
            bool result = false;
            int i = 0;
            while (i < MaxCount)
            {
                IHTMLElement element = doc3.getElementById("fwdButtonC.ID152");
                if (element != null)
                {
                    IHTMLAnchorElement anchor = (IHTMLAnchorElement)element;
                    if (anchor != null)
                    {
                        try
                        {
                            anchor.focus();
                            element.click();
                            result = true;
                            break;
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                i++;
            }

            return result;
        }

        public bool SelectProductCate(IHTMLDocument doc, IntPtr doc2Handle)
        { 
            HTMLDocumentClass docClass= (HTMLDocumentClass)doc;
            IHTMLElementCollection images = docClass.images;
            for(int i=0;i<images.length;i++)
            {
                IHTMLElement element = (IHTMLElement)images.item(i);
                HTMLImgClass img = (HTMLImgClass)element;
                if (img.src== "http://reserve.apple.com/rprcustomer/images/zh_CN/product/products_main_iphone4.png"
                    && img.alt == "iPhone")
                {
                    img.parentElement.click();
                    return true; 
                }
            }
            return false;
        }

        #endregion

        #region

        int i = 0;
        int status = 0;
        private void OpenButton_Click(object sender, EventArgs e)
        {
            if (MainWebBrowser.Url.ToString().ToLower() == ResourceManager.AppleData.StartUrl.ToLower())
            {
                if (i == 0)
                {
                    HtmlElementCollection selects = MainWebBrowser.Document.GetElementsByTagName("select");
                    foreach (HtmlElement select in selects)
                    {
                        if (select.Id == "storePopUpButton.ID148")
                        {
                            select.Focus();
                            SendKeys.Send("{DOWN}");
                            i++;
                        }
                    }
                }
                if (i == 1)
                {
                    MainWebBrowser.Document.GetElementById("fwdButtonC.ID152").InvokeMember("click");
                    status = 1;
                    i = 0;
                }
            }

            if(status ==1)// (MainWebBrowser.Url.ToString().ToLower() == "http://reserve.apple.com/WebObjects/ProductReservation.woa/wo/13.0.1.0.1.3.0.7.1.10.5".ToLower())
            {
                HtmlElementCollection images = MainWebBrowser.Document.GetElementsByTagName("img");
                foreach (HtmlElement img in images)
                {
                    if (img.GetAttribute("src") == "http://reserve.apple.com/rprcustomer/images/zh_CN/product/products_main_iphone4.png"
                        && img.GetAttribute("alt") == "iPhone")
                    {
                        img.Parent.InvokeMember("click");
                        status = 2;
                        i = 0;
                        break;
                    }
                }
            }
            if (status == 2)
            {
                if (i == 0)
                {
                    HtmlElementCollection allLis = MainWebBrowser.Document.GetElementsByTagName("li");
                    foreach (HtmlElement li in allLis)
                    {
                        if (li.InnerHtml.Substring(0, 3) == "8GB")  //"16GB","32GB"
                        {
                            li.Parent.NextSibling.InvokeMember("click");
                            i++;
                            break;
                        }
                    }
                }
                else if (i == 1)
                {
                    foreach (HtmlElement element in MainWebBrowser.Document.GetElementsByTagName("div"))
                    {
                        if (element.GetAttribute("class") == "grid2col outer")
                        {
                            HtmlElement parent = element.Children[1];
                         
                        }
                    }
                    //MainWebBrowser.Document.Forms["TheForm"].InvokeMember("submit", "/WebObjects/ProductReservation.woa/wo/13.0.1.0.1.3.0.7.25.10.1");
                    i = 0;
                    status = 3;
                }
            }
            if (status == 3)
            {
                MainWebBrowser.Document.GetElementById("appleid").SetAttribute("value","dingyuliang@msn.com");
                MainWebBrowser.Document.GetElementById("password").SetAttribute("value", "1q2w!Q@W");
                MainWebBrowser.Document.GetElementById("fwdButtonC").InvokeMember("click");
            }
            ///WebObjects/ProductReservation.woa/wo/7.0.1.0.1.3.0.7.9.10.1.15.1.1.1.1.1

        }
         
        #endregion

        #region Example

        public static InternetExplorer OpenNewIe(string url, string postData)
        {
            
            var ie = new InternetExplorer();  
            object vPost, vHeaders, vFlags, vTargetFrame;
            vPost = null;
            vFlags = null;
            vTargetFrame = null;
            vHeaders = "Content-Type: application/x-www-form-urlencoded" + Convert.ToChar(10) + Convert.ToChar(13);
            if (!string.IsNullOrEmpty(postData))
                vPost = ASCIIEncoding.ASCII.GetBytes(postData);
            ie.Visible = true;
            ie.Navigate(url, ref vFlags, ref vTargetFrame, ref vPost, ref vHeaders);
            return ie;
        }


        #endregion

        IHTMLDocument3 doc3 = null;
        public void SelectStore()
        {
            try
            { 
                IHTMLSelectElement storeOptions = null;
                int count = 10000;
                int i = 0;
                while (storeOptions == null && i < count)
                {
                    Thread.Sleep(20);
                    i++;
                    IHTMLElement2 select = (IHTMLElement2)doc3.getElementById("storePopUpButton.ID148");
                    if (select != null)
                    {
                        select.focus();
                        ((IHTMLSelectElement)select).selectedIndex = 3;
                        //SendKeys.Send("{ENTER}");
                        //MessageBox.Show("dddd");
                        break;
                    }
                } 
            }
            catch(Exception e) {
            
            } 
        }


        //Point point = new Point(300, 500);
        //SetCursorPos(400, 500);
        //mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
        //Thread.Sleep(100);
        //SetCursorPos(400, 560);
        //mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
        //Thread.Sleep(1000);
        //HtmlElement anchor = MainWebBrowser.Document.GetElementById("fwdButtonC.ID152");
        //anchor.Focus();
        //SendKeys.Send("{ENTER}"); //.InvokeMember("click");

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }

    public enum ProcessState
    {
        Started,
        Open
    }
    
}
